// @Author YaoYa
// @Date 2024-10-11 22:02:00
// @Desc
package api

import (
	"context"
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
	"math/rand"
	"mxshop-api/user-web/forms"
	"mxshop-api/user-web/global"
	"net/http"
	"strings"
	"time"
)

func CreateClient() (_result *dysmsapi20170525.Client, _err error) {
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
	// 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html。
	config := &openapi.Config{
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
		//LTAI5tJktjsVi7BMsA2Ejhp6
		//AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeyId: tea.String(global.ServerConfig.AliSmsInfo.AccessKeyId),

		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
		//R7IZofJYtjG5sSkOmt3792ewzE0u1Z
		AccessKeySecret: tea.String(global.ServerConfig.AliSmsInfo.AccessKeySecret),
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func GenerateSmsCode(with int) string {
	numberic := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numberic)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < with; i++ {
		fmt.Fprintf(&sb, "%d", numberic[rand.Intn(r)])
	}
	return sb.String()
}

func SendSms(ctx *gin.Context) {

	sendSmsForm := forms.SendSmsForm{}
	if err := ctx.ShouldBindJSON(&sendSmsForm); err != nil {
		//如何返回错误信息
		HandleValidatorError(ctx, err)
		return
	}
	smsCode := GenerateSmsCode(4)

	client, err := CreateClient()
	if err != nil {
		zap.S().Errorf("AliYun生成短信验证码错误,:", err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": "AliYun生成短信验证码错误",
		})
		return
	}

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(sendSmsForm.Mobile),
		SignName:      tea.String("golang学习签名"),
		TemplateCode:  tea.String("SMS_474440037"),
		TemplateParam: tea.String(fmt.Sprintf("{\"code\":\"%s\"}", smsCode)),
	}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		_, err = client.SendSmsWithOptions(sendSmsRequest, &util.RuntimeOptions{})
		if err != nil {
			return err
		}

		return nil
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
		// 错误 message
		fmt.Println(tea.StringValue(error.Message))
		// 诊断地址
		var data interface{}
		d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
		d.Decode(&data)
		if m, ok := data.(map[string]interface{}); ok {
			recommend, _ := m["Recommend"]
			fmt.Println(recommend)
		}
		_, err = util.AssertAsString(error.Message)
		if err != nil {
			zap.S().Errorf("AliYun生成短信验证码错误,:", err.Error())
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"msg": "AliYun生成短信验证码错误",
			})
			return
		}
	}

	//后面注册的时候会将短信验证码带回来注册，需要存储
	//验证码保存
	rdb := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
		Password: "", // no password set
		DB:       0,  // use default DB
		Protocol: 3,  // specify 2 for RESP 2 or 3 for RESP 3
	})

	rdb.Set(context.Background(), sendSmsForm.Mobile, smsCode, time.Duration(global.ServerConfig.AliSmsInfo.Expire)*time.Second)

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}
